package com.two.lbms.lzs.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.two.lbms.base.BaseService;
import com.two.lbms.dao.AdminMapper;
import com.two.lbms.lzs.query.AdminQuery;
import com.two.lbms.utils.AssertUtil;
import com.two.lbms.vo.Admin;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService extends BaseService<Admin,Integer> {
    //1.依赖注入 Dao层方法
    @Resource
    private AdminMapper adminMapper;

    /**
     * 一、 多条件分页查 管理员
     * @param query
     * @return
     */
    public Map<String,Object> queryAdminByParams(AdminQuery query){
        //2.新建 Map 集合对象，  LayUi格式数据  (key,value)
        Map<String,Object> map = new HashMap<>();
        //3.开始 分页 Page工具类
        PageHelper.startPage(query.getPage(), query.getLimit());
        //4. 定义分页信息
        PageInfo<Admin> pageInfo = new PageInfo<>(adminMapper.selectByParams(query));
        //5. 存到 集合中
        map.put("code",0);
        map.put("msg","success");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }

    /**
     * 2. 管理员 数据添加
     * @param admin
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveAdmin (AdminQuery adminQuery){
        //2.1 验证参数
        checkParams(adminQuery);
        Admin admin = new Admin();
        admin.setAdminName(adminQuery.getAdminName());
        admin.setAdminType(adminQuery.getAdminType());
        admin.setAdminPassword("123456");
        //2.2 设 默认值
        admin.setIsValid(1);//默认有效

        //2.3 添加 判结果
        AssertUtil.isTrue(adminMapper.insertSelective(admin) <1,"添加失败");
    }

    /**
     * 2.5 验 基参
     * @param adminName
     * @param adminPassword
     * @param adminType
     */
    private void checkParams(AdminQuery adminQuery) {
        // 1.调工具类
        AssertUtil.isTrue(StringUtils.isBlank(adminQuery.getAdminName()),"管理员不可为空");
        AssertUtil.isTrue(StringUtils.isBlank(adminQuery.getAdminType()),"管理员类型不可为空");
    }


    /**
     * 4. 管理员数据
     * @param
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public  void deleteAdmin (Integer id){

        Admin admin = new Admin();
        admin.setId(id);
        admin.setIsValid(0);
        //2. 删除 数据
        AssertUtil.isTrue(adminMapper.updateByPrimaryKeySelective(admin) < 1,"管理员注销失败！");
    }
}
